package com.example.esp8266.Main.Main_Fragment;

import android.annotation.SuppressLint;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import com.dlong.dl10netassistant.OnNetThreadListener;
import com.dlong.dl10netassistant.TcpClientThread;
import com.example.esp8266.R;

public class Connect_Fragment extends Fragment
        implements View.OnClickListener,OnNetThreadListener{

    private View root;
    private EditText ip_input,data_input,port_input;
    private TextView received_data_text;
    private boolean isConnected = false;
    private Button connectBtn;
    private String ipAddress,currentText,updatedText;
    private TcpClientThread tcp;

    private int ipPort;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        root = inflater.inflate(R.layout.connect_fragment, container, false);

        ip_input = root.findViewById(R.id.ip_data);
        port_input = root.findViewById(R.id.ip_port);
        data_input = root.findViewById(R.id.input_data);
        received_data_text = root.findViewById(R.id.receive_area);

        connectBtn = root.findViewById(R.id.connect_devices);//连接按钮
        Button input_dataBtn = root.findViewById(R.id.seed_mes);//发信按钮

        connectBtn.setOnClickListener(this);
        input_dataBtn.setOnClickListener(this);

        //以上为初始化

        ip_input.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                //
            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // 判断输入框原本的文字是否为空
                if (s.length() > 0) {
                    // 清除输入框原本的文字
                    ip_input.setText("");
                    // 移除 TextWatcher，确保只执行一次
                    ip_input.removeTextChangedListener(this);
                }
            }
            @Override
            public void afterTextChanged(Editable s) {
                //
            }
        });

        data_input.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                //
            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // 判断输入框原本的文字是否为空
                if (s.length() > 0) {
                    // 清除输入框原本的文字
                    data_input.setText("");
                    // 移除 TextWatcher，确保只执行一次
                    data_input.removeTextChangedListener(this);
                }
            }
            @Override
            public void afterTextChanged(Editable s) {
                //
            }
        });

        //以上为文本框输入时清除原字符串

        return root;
    }

    @Override//调用OnClickListener接口处理各种单击事件
    public void onClick(View v) {
        if (v.getId() == R.id.connect_devices) {
            if (isConnected) {
                // 断开连接的逻辑
                tcp.close();
                //Toast.makeText(Connect_DeviceActivity.this,"Disconnect",Toast.LENGTH_LONG).show();
                connectBtn.setText("连接设备"); // 修改按钮文本为 "Connect"
                isConnected = false;
            }
            else {
                // 连接的逻辑
                ipAddress = ip_input.getText().toString();
                ipPort = Integer.parseInt(port_input.getText().toString());
                tcp=new TcpClientThread(ipAddress,ipPort);
                tcp.start();
                tcp.setThreadListener(this); // 设置回调监听器
            }
        }
        else if (v.getId() == R.id.seed_mes) {
            String data = data_input.getText().toString();
            if(isConnected) {
                sendData(data);
                //Toast.makeText(Connect_DeviceActivity.this, "send data：" + data, Toast.LENGTH_LONG).show();
            }
            else {
                Toast.makeText(getActivity(), "Not connected to TCP server", Toast.LENGTH_LONG).show();
            }
        }
    }

    //以下为TCP处理

    // Send data method
    private void sendData(String data) {
        tcp.send(data.getBytes());
        // 获取现有内容
        currentText = received_data_text.getText().toString();
        // 添加新内容并换行
        updatedText = currentText + "\n" + "Send: " + data;
        // 设置更新后的内容
        received_data_text.setText(updatedText);

        // 获取 ScrollView 并自动滚动到底部
        ScrollView scrollView = root.findViewById(R.id.scrollView);
        scrollView.post(new Runnable() {
            @Override
            public void run() {
                scrollView.fullScroll(View.FOCUS_DOWN);
            }
        });
    }

    @Override
    public void onAcceptSocket(@NonNull String s) {

    }

    @Override
    public void onConnected(@NonNull String s) {
        if (getActivity() != null) {
            getActivity().runOnUiThread(new Runnable() {
                @SuppressLint("SetTextI18n")
                @Override
                public void run() {
                    //Toast.makeText(Connect_DeviceActivity.this, "已连接到：" + ipAddress, Toast.LENGTH_LONG).show();
                    received_data_text.setText("Client: 已连接到：" + ipAddress + ":" + ipPort + "\n");
                    connectBtn.setText("断开连接"); // 修改按钮文本为 "断开连接"
                    isConnected = true;
                }
            });
        }
    }

    @Override
    public void onConnectFailed(@NonNull String s) {
        if (getActivity() != null) {
            getActivity().runOnUiThread(new Runnable() {
                @SuppressLint("SetTextI18n")
                @Override
                public void run() {
                    //Toast.makeText(Connect_DeviceActivity.this, "连接失败，请检查地址是否正确", Toast.LENGTH_LONG).show();
                    received_data_text.setText("Client: 连接到-" + "'" + ipAddress + ":" + ipPort + "'-" + "失败，请检查地址是否正确");
                }
            });
        }
    }

    @Override
    public void onDisconnect(@NonNull String s) {
        if (getActivity() != null) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    received_data_text.setText("未建立任何连接");
                    connectBtn.setText("连接设备"); // 修改按钮文本为 "Connect"
                    isConnected = false;
                }
            });
        }
    }

    @Override
    public void onError(@NonNull String s, @NonNull String s1) {
        if (getActivity() != null) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    // 显示错误信息
                    Toast.makeText(getActivity(), "Error: " + s1, Toast.LENGTH_LONG).show();
                }
            });
        }
    }

    @Override
    public void onReceive(@NonNull String s, int i, long l, @NonNull byte[] bytes) {
        // 将 bytes 转换为字符串
        final String receivedData = new String(bytes);

        // 确保 UI 更新在主线程中进行
        if (getActivity() != null) {
            getActivity().runOnUiThread(new Runnable() {
                @SuppressLint("SetTextI18n")
                @Override
                public void run() {
                    // 获取现有内容
                    currentText = received_data_text.getText().toString();
                    // 添加新内容并换行
                    updatedText = currentText + "\n" + "Receive: " + receivedData;
                    // 设置更新后的内容
                    received_data_text.setText(updatedText);

                    // 获取 ScrollView 并自动滚动到底部
                    ScrollView scrollView = root.findViewById(R.id.scrollView);
                    scrollView.post(new Runnable() {
                        @Override
                        public void run() {
                            scrollView.fullScroll(View.FOCUS_DOWN);
                        }
                    });
                }
            });
        }
    }
    //TCP处理-完

}

